package system

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"jgyApi/server/global"
	"jgyApi/server/model/common/response"
	"jgyApi/server/model/system"
	systemReq "jgyApi/server/model/system/request"
	systemRes "jgyApi/server/model/system/response"
	"jgyApi/server/utils"
	"strings"
	"time"
)

type AppApi struct{}

func (a *AppApi) RunAppRestrictList(c *gin.Context) {
	var co systemReq.CommonSn
	err := c.ShouldBind(&co)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(co, utils.SnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	var rs utils.CacheResult
	rs = utils.GetRedisCacheField("sn", "value", co.Sn, "batch")
	if rs.Data == nil || rs.Data == "" {
		response.FailWithMessage("该设备没有设置批次", c)
		return
	}
	var appRestrict system.RunAppRestrict
	where := fmt.Sprintf("find_in_set(%s,batch)", rs.Data)
	err = global.GVA_DB.Model(&system.RunAppRestrict{}).Where(where).First(&appRestrict).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}
	res := strings.Split(*appRestrict.PackageName, ",")
	response.OkWithData(res, c)
}

func (a *AppApi) GetEbagCode(c *gin.Context) {
	var ks systemReq.KeySn
	err := c.ShouldBind(&ks)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(ks, utils.KeySnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//校验key
	if !utils.IsThrough(ks.Key) {
		response.FailWithMessage("key不对", c)
		return
	}

	var sn system.Sn
	err = global.GVA_DB.Model(&system.Sn{}).Where("value=?", ks.Sn).First(&sn).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}

	var esn system.EbagSn
	err = global.GVA_DB.Model(&system.EbagSn{}).Where("sn_id=?", sn.ID).First(&esn).Error
	if err != nil {
		response.FailWithMessage("该sn没有电子书包", c)
		return
	}
	var esCode system.EbagCode
	err = global.GVA_DB.Model(&system.EbagCode{}).Where("sn_id in ?", []int64{esn.ID, 0}).Order("sn_id DESC").First(&esCode).Error
	if err != nil {
		response.FailWithMessage("电子书包激活码已经用完", c)
		return
	}

	nowTime := time.Now().Unix()
	err = global.GVA_DB.Model(&esCode).Updates(system.EbagCode{ActivationTime: &nowTime, SnID: &sn.ID}).Error
	if err != nil {
		response.FailWithMessage("error", c)
		return
	}
	response.OkWithMessage("success", c)
	return
}

func (a *AppApi) GetFirmwareApp(c *gin.Context) {
	var ksv systemReq.KeySnVersion
	err := c.ShouldBind(&ksv)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(ksv, utils.KeySnVersionVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//校验key
	if !utils.IsThrough(ksv.Key) {
		response.FailWithMessage("key不对", c)
		return
	}
	var firmwareApp system.FirmwareApp
	err = global.GVA_DB.Model(&system.FirmwareApp{}).Where("version_number=?", ksv.VersionNumber).First(&firmwareApp).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}
	response.OkWithDetailed(system.FirmwareApp{PackageName: firmwareApp.PackageName}, "success", c)
}

func (a *AppApi) Silent(c *gin.Context) {
	var pt systemReq.PackageType
	err := c.ShouldBind(&pt)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	type update struct {
		ID          int64   `gorm:"column:id;type:int(100) unsigned;primaryKey;autoIncrement:true;comment:ID" json:"id"`
		AppName     *string `gorm:"column:app_name;type:varchar(255);comment:应用名" json:"app_name"`
		Package     *string `gorm:"column:package;type:varchar(100);comment:应用包名" json:"package"`
		VersionCode *int64  `gorm:"column:version_code;type:int(10);comment:版本代码" json:"version_code"`
		URL         *string `gorm:"column:url;type:varchar(255);comment:下载地址" json:"url"`
		AppMd5      *string `gorm:"column:app_md5;type:varchar(255)" json:"app_md5"`
	}
	var r update
	err = global.GVA_DB.Model(&system.Update{}).Where("package=?", pt.Package).Where("type=?", pt.Type).First(&r).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}
	response.OkWithDetailed(r, "success", c)
	return
}

func (a *AppApi) LabelIndex (c *gin.Context) {
	var ks systemReq.KeySn
	err := c.ShouldBind(&ks)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	var rs utils.CacheResult
	rs = utils.GetRedisCacheField("sn", "value", ks.Sn, "batch")
	if rs.Data == nil || rs.Data == "" {
		response.FailWithMessage("该设备没有设置批次", c)
		return
	}
	type label struct {
		HomePage   string  `gorm:"column:home_page;type:text;not null;comment:主页" json:"home_page"`
		LabelPage  *string `gorm:"column:label_page;type:text;comment:标签页" json:"label_page"`
	}
	var l label
	where := fmt.Sprintf(" find_in_set(%s,batch)", rs.Data)
	err = global.GVA_DB.Model(&system.Label{}).Where(where).First(&l).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}
	response.OkWithDetailed(l, "success", c)
}

//
// RankIndex
//  @Description: 热门推荐专属
//  @receiver a
//  @param c
//
func (a *AppApi) RankIndex(c *gin.Context) {
	var ks systemReq.KeySn
	err := c.ShouldBind(&ks)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(ks, utils.KeySnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if !utils.IsThrough(ks.Key) {
		response.FailWithMessage("key不对", c)
		return
	}

	var sn system.Sn
	err = global.GVA_DB.Where("value=?", ks.Sn).First(&sn).Error
	if err != nil {
		response.FailWithDetailed([]string{}, "没有找到sn码", c)
		return
	}
	if *sn.IsLock != 1 {
		response.FailWithMessage("没有找到数据", c)
		return
	}

	var apps []system.App
	where := fmt.Sprintf("find_in_set(%s,app_batch)", *sn.Batch)
	err = global.GVA_DB.Where(where).Where("app_admin_id=?", sn.AdminID).Where("app_attribution=?", 1).Where("is_delete=?", 1).Find(&apps).Error
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	for k,v := range apps {
		apps[k].AppPackage = v.Bg
	}
	response.OkWithDetailed(apps, "success", c)
	return

}
//
// CommonApp
//  @Description: 热门推荐之公共应用
//  @receiver a
//  @param c
//

func (a *AppApi) CommonApp(c *gin.Context)  {
	var ks systemReq.KeySn
	err := c.ShouldBind(&ks)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(ks, utils.KeySnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if !utils.IsThrough(ks.Key) {
		response.FailWithMessage("key不对", c)
		return
	}
	var sn system.Sn
	err = global.GVA_DB.Where("value=?", ks.Sn).First(&sn).Error
	if err != nil {
		response.FailWithDetailed([]string{}, "没有找到sn码", c)
		return
	}
	if *sn.IsLock != 1 || *sn.Batch == "" {
		response.FailWithMessage("没有找到数据", c)
		return
	}
	var apps []system.App
	err = global.GVA_DB.Where("app_admin_id=?", sn.AdminID).Where("app_attribution=?", 0).Where("is_delete=?", 1).Where("app_status=?", "normal").Order("app_downloads DESC").Find(&apps).Error

	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	for k, v := range apps {
		apps[k].AppPackage = v.Bg
	}

	response.OkWithDetailed(apps, "success", c)
	return
}

func (a *AppApi) AppGroundIndex(c *gin.Context)  {

	var ks systemReq.KeySn
	err := c.ShouldBind(&ks)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(ks, utils.KeySnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if !utils.IsThrough(ks.Key) {
		response.FailWithMessage("key不对", c)
		return
	}

	var rs utils.CacheResult
	rs = utils.GetRedisCacheField("sn", "value", ks.Sn, "batch")
	if rs.Data == nil || rs.Data == "" {
		response.FailWithMessage("该设备没有设置批次", c)
		return
	}

	var res []systemRes.AppGroundIndexResponse
	where := fmt.Sprintf("find_in_set(%s,batch)", rs.Data)

	err = global.GVA_DB.Model(&system.AppGround{}).Where(where).Group("package,address,type").Find(&res).Error

	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}

	response.OkWithDetailed(res, "success", c)
	return
}